<template>
  <div>
    <ksd-banner-vip></ksd-banner-vip>
    <div class="flex1">
      <div v-if="noteList && noteList.length > 0">
        <div class="module owl-dynamic alert-primary">
          <ksd-scroll-list></ksd-scroll-list>
          <span class="fw red mr10 fz12">遇到问题，联系飞哥微信：xuchengfeifei</span>
        </div>
        <ksd-scroll-message></ksd-scroll-message>
        <div class="ssd-contentbox">
          <div>
            <div class="flex align-center justify-center flex-c" v-if="loadingFlag">
              <k-loading show></k-loading>
              <span class="fz18 c666 fb ml20">正在加载中</span>
            </div>
            <div class="file-list-container" v-if="!loadingFlag">
              <div class="setting-content tootip-file-content-common">
                <div class="setting-content-grid">
                  <div>
                    <span>你关注的：</span>
                    <ul class="setting-tabs">
                      <li class="setting-tab" v-for="key in selectKeywords">{{ key }}</li>
                    </ul>
                    <button class="reset-btn" @click="handleReset">重置</button>
                  </div>
                  <div class="flex align-center">
                    <ul class="setting-tabs">
                      <li class="setting-tab opened" :class="[changeIndex==0?'active fw':'']"
                          @click="handleLoadSort(0)">最新
                      </li>
                      <li class="setting-tab updated" :class="[changeIndex==1?'active fw':'']"
                          @click="handleLoadSort(1)">热门
                      </li>
                    </ul>
                    <div class="right">
                      共<span class="fw ml2 mr2">{{ total }}</span>条
                    </div>
                  </div>
                </div>
              </div>
              <div class="file-card-content">
                <div class="card-grid mb30">
                  <div class="itemcard animate__fadeIn animate__animated" :class="['animate__delay-'+(num+1)+'s']"
                       v-for="(item,index) in noteList" :key="index">
                    <nuxt-link :href="'/note/'+(item.chapterFlag==1?'page':'detail')+'/'+item.id" :title="item.title">
                      <div class="entry-media">
                        <img
                            :src="item.img"
                            :alt="item.title"
                            :title="item.title"
                            class="item-pic"/>
                      </div>
                      <div class="entry-wrapper">
                <span class="meta-category-dot" v-if="item.tags && item.tags.length > 0">
                  <template v-for="(tag,index) in item.tags.split(',')" :key="index">
                    <a href="javascript:void(0);">
                      <i class="dot"></i>{{ tag }}
                    </a>
                  </template>
                </span>
                        <h1 class="item-title">{{ item.title }}</h1>
                        <p class="item-desc">{{ item.description }}</p>
                      </div>
                      <div class="entry-footer">
                        <div class="entry-meta">
                  <span class="meta-date">
                    <time :datetime="formatMsgTime(item.createTime)">
                      <i class="iconfont icon-shijian pr tp2"></i><span class="ml3">{{
                        formatMsgTime(item.createTime)
                      }}</span>
                    </time>
                   </span>
                          <span class="meta-views ml10 pr tp2"><i class="iconfont icon-eye"></i><span
                              class="ml2 pr ftp2">{{ item.viewcount || 0 }}</span></span>
                          <span class="meta-shhop-icon  pr tp1" v-if="changeIndex < 2">
                    <i class="iconfont icon-a-dagang1"></i>
                    <span class="ml2 pr ftp1">{{ item.categoryName }}</span>
                  </span>
                          <span class="meta-shhop-icon pointer pr ftp1"
                                @click.prevent="handleNoteCancelBroswer(item.id,index)" v-if="changeIndex==2"><i
                              class="iconfont icon-shanchu4 pr tp2"></i>删除足迹</span>
                          <span class="meta-shhop-icon pointer pr ftp1"
                                @click.prevent="handleNoteCancelFav(item.id,index)" v-if="changeIndex==3"><i
                              class="iconfont icon-shanchu4 pr tp2"></i>取消收藏</span>
                        </div>
                      </div>
                    </nuxt-link>
                  </div>
                </div>
                <k-empty :show="total == 0"></k-empty>
                <div @click="handleLoadMore" v-if="total > queryParams.pageSize && queryParams.pageNo < pages"
                     class="flex justify-center pointer">加载更多({{ total || 0 }})
                </div>
                <div v-if="total > queryParams.pageSize && queryParams.pageNo == pages"
                     class="flex justify-center c999 mt20 mb20">没有更多了
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="tagsbox flex justify-center align-center w100"
           style="height: calc(100vh - 128px);">
        <div class="container flex justify-center align-center flex-c">
          <h1 class="fz28 fw mb30">请选择你关注的关键词</h1>
          <div class="flex justify-center align-center" style="flex-wrap: wrap;">
            <div class="tags" :class="[item.checked?'checked':'']" v-for="(item,index) in allKeywords"
                 @click="handleChecked(index)">{{ item.keyword }}
            </div>
          </div>
          <div class="mt20">
            <button class="sure-btn" @click="handleSure"><i class="iconfont icon-icon_right mr5"></i>确定</button>
            <button class="cancel-btn" @click="handleCancel"><i class="iconfont icon-shuaxin mr5"></i>重置</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
const selectKeywords = ref([])
const allKeywords = ref([])
const userStore = useStore.userState()
const noteList = ref([])
const loadingFlag = ref(false)
const route = useRoute()
const changeIndex = ref(0)
const categoryIndex = ref(-1)
const total = ref(0)
const pages = ref(0)
const queryParams = reactive({
  channelId: 0,
  categoryId: 0,
  keyword: "",
  notetype: 0,  // 基础课 2进阶课 3 实战小册 4 面试课
  pageNo: 1,
  pageSize: 42,
  orderNum: 0 // 0 最新  1 最热 2 最后更新
})

const props = defineProps({
  channelId: {
    type: Number,
    default: 0
  }
})

const handleSearch = async () => {
  if (!queryParams.keyword) {
    getDom("keyword").focus()
    useMessage().info("请输入搜索关键词")
    return;
  }
  queryParams.pageNo = 1
  noteList.value = []
  handleLoadData()
}


const handleLoadDataKeyword = (keywords) => {
  queryParams.keyword = keywords.join(",")
  handleLoadData()
}


const handleLoadData = async () => {
  queryParams.channelId = props.channelId
  loadingFlag.value = true
  const resp = await useLoadNoteApi(queryParams)
  noteList.value = noteList.value.concat(resp.data.records)
  total.value = resp.data.total
  pages.value = resp.data.pages
  loadingFlag.value = false
}

const handleLoadSort = (sortnum) => {
  noteList.value = []
  queryParams.pageNo = 1
  changeIndex.value = sortnum
  queryParams.orderNum = sortnum
  categoryIndex.value = -1
  handleLoadData()
}

const handleLoadMore = () => {
  queryParams.pageNo++
  handleLoadData()
}


//取消收藏
const handleNoteCancelFav = (id, index) => {
  useDialog().warning({
    content: "你确定要【取消收藏】此课程吗？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: async () => {
      try {
        // 退出逻辑
        await useCancelFavNoteApi(id)
        noteList.value.splice(index, 1)
        total.value--
        if (noteList.value.length == 0) {
          handleLoadSort(changeIndex.value)
        }
      } catch (e) {
        useMessage().error(e.message)
      }
    }
  })
}

//删除记录
const handleNoteCancelBroswer = (id, index) => {
  useDialog().warning({
    content: "你确定【删除记录】吗？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: async () => {
      try {
        // 退出逻辑
        await useRemoveNoteHitsApi(id)
        noteList.value.splice(index, 1)
        total.value--
        if (noteList.value.length == 0) {
          handleLoadSort(changeIndex.value)
        }
      } catch (e) {
        useMessage().error(e.message)
      }
    }
  })
}

const handleChecked = (index) => {
  allKeywords.value[index].checked = !allKeywords.value[index].checked
  var key = allKeywords.value[index].keyword
  if (allKeywords.value[index].checked) {
    var index = selectKeywords.value.findIndex(c => c == key)
    if (index == -1) {
      selectKeywords.value.push(key)
    } else {
      selectKeywords.value.splice(index, 1)
    }
  } else {
    var index = selectKeywords.value.findIndex(c => c == key)
    selectKeywords.value.splice(index, 1)
  }
}

watch(selectKeywords, (newVal, oldVal) => {
  localStorage.setItem("kk-search-keywords", JSON.stringify(newVal))
}, {
  deep: true
})

const handleSure = async () => {
  await useLoginDialog()
  var len = allKeywords.value.filter(c => c.checked).length
  if (len == 0) {
    useMessage().warning("请选择关键词");
    return
  }
  if (selectKeywords.value.length > 3 && userStore.viptype == 1) {
    useMessage().warning("非VIP最多选择3个！")
    return
  }

  if (selectKeywords.value.length > 10 && userStore.viptype > 1) {
    useMessage().warning("最多选择10个！")
    return
  }
  selectKeywords.value = allKeywords.value.filter(c => c.checked).map(c => c.keyword)
  handleLoadDataKeyword(selectKeywords.value)
}


const handleCancel = () => {
  allKeywords.value.map(c => {
    c.checked = false
    return c
  })
  selectKeywords.value = []
  noteList.value = []
}

const handleReset = () => {
  noteList.value = []
}

const handleLoadDataKeys = async () => {
  const resp = await useLoadSearchKeywords()
  allKeywords.value = resp.data.map(c => {
    c.checked = false
    return c
  })

  var cacheKeywords = localStorage.getItem("kk-search-keywords")
  if (cacheKeywords) {
    selectKeywords.value = JSON.parse(cacheKeywords)
    if (selectKeywords.value && selectKeywords.value.length > 0) {
      allKeywords.value.map(c => {
        c.checked = selectKeywords.value.findIndex(cc => cc == c.keyword) != -1
        return c
      })
      handleLoadDataKeyword(selectKeywords.value)
    }
  }
}

definePageMeta({
  layout: "nindex"
})

onMounted(async () => {
  await handleLoadDataKeys()
})

</script>

<style scoped lang="scss">
.tagsbox {
  width: 1120px;

  .tags {
    border: 1px solid #eee;
    margin: 5px;
    padding: 6px 20px;
    border-radius: 4px;
    cursor: pointer;
  }

  .tags:hover, .tags.checked {
    background: #45c985;
    color: #fff;
  }
}

.reset-btn {
  border: 1px solid #eee;
  padding: 2px 20px;
  color: #fff;
  margin: 0 10px;
  border-radius: 4px;
  background: #45c985;
}


.sure-btn, .cancel-btn {
  border: 1px solid #eee;
  padding: 6px 32px;
  margin: 0 10px;
  border-radius: 4px;
}

.sure-btn {
  background: #45c985;
  color: #fff;
}
</style>
